/**
 * @Author: LiMeng
 * @Date: 2017/4/28
 */
var GLOBAL = {
    ID: '',
    CONTRACTOR_ID: '',
    ACTION_URL: '',
    DATA_GRID_ROW_INDEX: {
        dg1: 0
    },
    YEARS: []
};
var getSelectedUser = function (data) {
    var names = '';
    var ids = '';
    for (var index in data) {
        names += ',' + data[index].realName;
        ids += ',' + data[index].id;
    }

    $('#teacherName').textbox('setValue', names.substring(1));
    $('#teacherId').val(ids.substring(1));
};
var getSelectedContractorStaff = function (data, target) {
    if (target === null || target === '') {
        return;
    }
    data = data[0];
    var $dg = $('#dg1');
    var index = $dg.datagrid('getRowIndex', target);
    var $personName = $dg.datagrid('getEditor', {index: index, field: 'personName'});
    var $personId = $dg.datagrid('getEditor', {index: index, field: 'personId'});
    var $idcard = $dg.datagrid('getEditor', {index: index, field: 'idcard'});
    var $contractorName = $dg.datagrid('getEditor', {index: index, field: 'contractorName'});
    var $contractorId = $dg.datagrid('getEditor', {index: index, field: 'contractorId'});
    $($personName.target).textbox('setValue', data.name);
    $($personId.target).textbox('setValue', data.id);
    $($idcard.target).textbox('setValue', data.idcard);
    $($contractorName.target).textbox('setValue', data.contractorName);
    $($contractorId.target).textbox('setValue', data.contractorId);

};
var openSelectContractorStaff = function (title, target) {
    title = title || '请选择承包商人员';

    WindowManager.openLayer({
        type: 2,
        title: title,
        area: ['700px', '400px'],
        content: ROOT_PATH + '/contractor/contractorStaff/simpleList.shtml?contractorId=' + GLOBAL.CONTRACTOR_ID,
        callBack: function (data) {
            getSelectedContractorStaff(data, target);
        }
    });
};
var openSelectUser = function (title) {
    layer.open({
        type: 2,
        title: title,
        area: ['900px', '500px'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml' + '?isMulti=1'
    });
};
var getRecentTwentyYearsComboList = function () {
    var thisYear = new Date().getFullYear();
    for (var i = thisYear + 10; i > thisYear - 10; i--) {
        GLOBAL.YEARS.push({
            value: i,
            text: i
        });
    }
};
var toggleComboBox = function () {
    var $isTrainOutside = $('#isTrainOutside');
    var $trainDeptId = $('#trainDeptId');
    var $trainDeptNameOutside = $('#trainDeptNameOutside');
    var $wrap_trainDeptId = $trainDeptId.parents('.form_one');
    var $wrap_trainDeptNameOutside = $trainDeptNameOutside.parents('.form_one');

    if ($isTrainOutside.val().toString() === '0') {
        $trainDeptId.textbox('enable');
        $trainDeptNameOutside.textbox('disable');
    } else {
        $trainDeptId.textbox('disable');
        $trainDeptNameOutside.textbox('enable');
    }

    $isTrainOutside.combobox({
        onChange: function () {
            if ($(this).val().toString() === '0') {
                $wrap_trainDeptId.removeClass('hide');
                $wrap_trainDeptNameOutside.addClass('hide');
                $trainDeptId.textbox('enable');
                $trainDeptNameOutside.textbox('disable');
            } else {
                $wrap_trainDeptId.addClass('hide');
                $wrap_trainDeptNameOutside.removeClass('hide');
                $trainDeptId.textbox('disable');
                $trainDeptNameOutside.textbox('enable');
            }
        }
    });
};
var toggleFieldDisableState = function (state) {
    $('#name').textbox(state);
    $('#year').textbox(state);
    $('#trainTypeId').textbox(state);
    $('#trainStartTime').textbox(state);
    $('#trainEndTime').textbox(state);
    $('#actualTrainHour').textbox(state);
    $('#teacherName').textbox(state);
    $('#teacherNameOutside').textbox(state);
    $('#isTrainOutside').textbox(state);
    $('#trainDeptId').textbox(state);
    $('#trainDeptNameOutside').textbox(state);
    $('#needCertificate').textbox(state);
    $('#trainNum').textbox(state);
    $('#qualifiedNum').textbox(state);
    $('#trainContent').textbox(state);
    $('#trainSummary').textbox(state);
    $('#examMode').textbox(state);
};
var hideButtons = function () {
    $('.menu-right').addClass('hide');
    $('#dg1_btn_add').addClass('hide');
    $('#dg1').datagrid('hideColumn', 'action');
};
var setElementWithState = function () {
    var state = $.getQueryParam('state');
    if (state === 'edit') {
        GLOBAL.ID = $.getQueryParam("id");
        GLOBAL.ACTION_URL = ROOT_PATH + '/contractor/staffTrain/edit.shtml';
    } else if (state === 'copy') {
        $('#trainNum').textbox('setValue', 0);
        $('#qualifiedNum').textbox('setValue', 0);
        GLOBAL.ACTION_URL = ROOT_PATH + '/contractor/staffTrain/add.shtml';
    } else {
        toggleFieldDisableState('disable');
        hideButtons();
    }
};
var attachEditRowEvent = function (dataGridId) {
    $('body').on('click', '[id^=' + dataGridId + '_btn_edit_]', function () {
        var id = this.id.replace(dataGridId + '_btn_edit_', '');
        var dgEle = '#' + dataGridId;
        var index = $(dgEle).datagrid('getRowIndex', id);
        $(dgEle).datagrid('selectRow', index).datagrid('beginEdit', index);
        $(this).addClass('hide');
        $('#' + dataGridId + '_btn_save_' + id).removeClass('hide');
        $('#' + dataGridId + '_btn_delete_' + id).addClass('hide');
        $('#' + dataGridId + '_btn_cancel_' + id).removeClass('hide');
    });
};
var attachSaveRowEvent = function (dataGridId, url) {
    $('body').on('click', 'a[id^=' + dataGridId + '_btn_save_]', function () {
        var $this = $(this);
        var id = this.id.replace(dataGridId + '_btn_save_', '');
        var dgEle = '#' + dataGridId;
        var index = $(dgEle).datagrid('getRowIndex', id);
        if ($(dgEle).datagrid('validateRow', index)) {
            $(dgEle).datagrid('endEdit', index);
            $.ajax({
                method: 'POST',
                dataType: 'json',
                url: url,
                data: $(dgEle).datagrid('getSelected'),
                success: function (result) {
                    if (result.success) {
                        $.messager.progress('close');	// 如果提交成功则隐藏进度条
                        layer.msg(result.message, {time: 1000, icon: 1}, function () {
                            $this.addClass('hide');
                            $('#' + dataGridId + '_btn_edit_' + id).removeClass('hide');
                            $('#' + dataGridId + '_btn_delete_' + id).removeClass('hide');
                            $('#' + dataGridId + '_btn_cancel_' + id).addClass('hide');
                        });
                    } else {
                        $.messager.progress('close');
                        layer.msg(result.message, {time: 1000, icon: 2});
                    }
                }
            });
        }
    });
};
var attachCancelRowEvent = function (dataGridId) {
    $('body').on('click', 'a[id^=' + dataGridId + '_btn_cancel_]', function () {
        var id = this.id.replace(dataGridId + '_btn_cancel_', '');
        var dgEle = '#' + dataGridId;
        var index = $(dgEle).datagrid('getRowIndex', id);
        $(dgEle).datagrid('cancelEdit', index);
        $(this).addClass('hide');
        $('#' + dataGridId + '_btn_save_' + id).addClass('hide');
        $('#' + dataGridId + '_btn_edit_' + id).removeClass('hide');
        $('#' + dataGridId + '_btn_delete_' + id).removeClass('hide');
    });
};
var attachDeleteRowEvent = function (dataGridId, url) {
    $('body').on('click', 'a[id^=' + dataGridId + '_btn_delete_]', function () {
        var $this = $(this);
        var layIndex = layer.confirm('确定删除本条数据吗？', function () {
            var id = $this[0].id.replace(dataGridId + '_btn_delete_', '');
            var dgEle = '#' + dataGridId;
            var index = $(dgEle).datagrid('getRowIndex', id);
            $.ajax({
                method: 'POST',
                dataType: 'json',
                url: url,
                data: {
                    id: $(dgEle).datagrid('getSelected').id
                },
                success: function (result) {
                    if (result.success) {
                        layer.msg(result.message, {time: 1000, icon: 1}, function () {
                            $(dgEle).datagrid('deleteRow', index);
                            GLOBAL.DATA_GRID_ROW_INDEX[dataGridId] -= 1;
                        });
                    } else {
                        layer.msg(result.message, {time: 1000, icon: 2});
                    }
                }
            });
            layer.close(layIndex);
        });
    });
};
var attachAddRowEvent = function (dataGridId, url) {
    $('#' + dataGridId + '_btn_add').on('click', function () {
        if ($.getQueryParam('state') === 'copy') {
            layer.alert('为防止数据丢失，请先保存！');
            return false;
        }
        var id = $.generateUUID();
        $.ajax({
            method: 'POST',
            dataType: 'json',
            url: url,
            data: {
                id: id,
                trainId: GLOBAL.ID
            },
            success: function (result) {
                if (!result.success) {
                    layer.msg(result.message, {time: 1000, icon: 2});
                    return false;
                }
                $('#' + dataGridId).datagrid('insertRow', {
                        index: GLOBAL.DATA_GRID_ROW_INDEX[dataGridId],
                        row: {
                            id: id,
                            trainId: GLOBAL.ID
                        }
                    }
                ).datagrid('selectRow', GLOBAL.DATA_GRID_ROW_INDEX[dataGridId]).datagrid('beginEdit', GLOBAL.DATA_GRID_ROW_INDEX[dataGridId]);
                $('#' + dataGridId + '_btn_edit_' + id).addClass('hide');
                $('#' + dataGridId + '_btn_save_' + id).removeClass('hide');
                $('#' + dataGridId + '_btn_delete_' + id).addClass('hide');
                $('#' + dataGridId + '_btn_cancel_' + id).removeClass('hide');
                GLOBAL.DATA_GRID_ROW_INDEX[dataGridId] += 1;
            }
        });
    });
};
$(function () {
    getRecentTwentyYearsComboList();

    $('#trainTypeId').combobox({
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml?code=' + CONSTANT.DictionaryTypeDefConstants.CONTRACTOR_TRAIN_TYPE,
        valueField: 'id',
        textField: 'text',
        required: true,
        editable: false
    });

    $('#year').combobox({
        data: GLOBAL.YEARS,
        value: new Date().getFullYear(),
        editable: false,
        required: true
    });

    $('#teacherName').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectUser('选择授课人');
            }
        }],
        editable: false
    });

    $('#trainDeptId').combotree({
        url: ROOT_PATH + '/permission/department/getDepartmentTree.shtml?parentId=0',
        required: true,
        editable: false
    });

    $('#dg1').datagrid({
        method: 'post',
        url: ROOT_PATH + '/contractor/trainee/list.shtml',
        queryParams: {
            trainId: GLOBAL.ID,
            sort: 'addTime',
            order: 'desc'
        },
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: false,
        height: 300,
        singleSelect: true,
        columns: [[
            {field: 'ckid', checkbox: true},
            {field: 'personId', hidden: true, editor: {type: 'textbox', options: {required: true}}},
            {field: 'contractorId', hidden: true, editor: {type: 'textbox', options: {required: true}}},
            {
                field: 'action', title: '操作', width: 60, align: 'center', formatter: function (value, row, index) {
                var ele_edit = '<a id="dg1_btn_edit_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary" plain="true">编辑</a> ';
                var ele_save = '<a id="dg1_btn_save_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary hide" plain="true">保存</a> ';
                var ele_delete = '<a id="dg1_btn_delete_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary" plain="true">删除</a>';
                var ele_cancel = '<a id="dg1_btn_cancel_' + row.id + '" href="javascript:void(0)" class="easyui-linkbutton text-primary hide" plain="true">取消</a>';
                return ele_edit + ele_save + ele_delete + ele_cancel;
            }
            },
            {
                field: 'personName',
                title: '姓名',
                width: 80,
                sortable: true,
                editor: {
                    type: 'textbox',
                    editable: false,
                    options: {
                        required: true,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                var id = $(this).parents('.datagrid-row').find('[name=id]').val();
                                openSelectContractorStaff('选择授课人', id);
                            }
                        }]
                    }
                }
            },
            {
                field: 'idcard',
                title: '身份证号',
                width: 80,
                editor: {type: 'textbox', options: {editable: false, required: true, validType: 'idcn'}}
            },
            {
                field: 'contractorName',
                title: '承包商名称',
                width: 100,
                editor: {type: 'textbox', options: {editable: false, required: true}}
            },
            {
                field: 'score',
                title: '成绩',
                width: 60,
                sortable: true,
                editor: {type: 'numberspinner', options: {required: true}}
            },
            {
                field: 'isQualified',
                title: '是否合格',
                width: 50,
                sortable: true,
                formatter: function (value) {
                    if (value && value.toString() === '1') {
                        return '是';
                    }
                    return '否';
                },
                editor: {
                    type: 'combobox', options: {
                        required: true,
                        data: [{
                            value: 1,
                            text: '是'
                        }, {
                            value: 0,
                            text: '否'
                        }]
                    }
                }
            },
            {
                field: 'workTerm',
                title: '作业有效期限',
                width: 100,
                sortable: true,
                editor: {type: 'datebox'}
            },
            {
                field: 'workType',
                title: '工种',
                width: 80,
                sortable: true,
                editor: {type: 'textbox'}
            },
            {field: 'addTime', title: '登记日期', width: 100, sortable: true},
            {field: 'trainId', title: '培训记录id', hidden: true}
        ]]
    });

    toggleComboBox();

    setElementWithState();

    $('#btn_save').on('click', function () {
        $.messager.progress();	// 显示进度条

        $('#form1').form('submit', {
            url: GLOBAL.ACTION_URL,
            onSubmit: function (param) {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// 如果表单是无效的则隐藏进度条
                }
                return isValid;	// 返回false终止表单提交
            },
            success: function (result) {
                result = $.parseJSON(result);
                if (result.success) {
                    $.messager.progress('close');	// 如果提交成功则隐藏进度条
                    layer.msg(result.message, {time: 1000, icon: 1}, function () {
                        $.getIframeWindow().$('#dg1').datagrid('load');
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                    });
                } else {
                    $.messager.progress('close');	// 如果提交成功则隐藏进度条
                    layer.msg(result.message, {icon: 2});
                }
            }
        });
    });

    //添加按钮
    attachAddRowEvent('dg1', ROOT_PATH + '/contractor/trainee/save.shtml');
    //每行的编辑按钮
    attachEditRowEvent('dg1');
    //每行的保存按钮
    attachSaveRowEvent('dg1', ROOT_PATH + '/contractor/trainee/update.shtml');
    //每行的取消按钮
    attachCancelRowEvent('dg1');
    //每行的删除按钮
    attachDeleteRowEvent('dg1', ROOT_PATH + '/contractor/trainee/delete.shtml');
});